package com.david.mydemo.ctl_es.controller;

import com.alibaba.fastjson.JSON;
import com.david.mydemo.ctl_es.dto.ResponseEsDemoDto;
import com.david.mydemo.ctl_es.dto.ResponseResultDto;
import com.david.mydemo.ctl_es.model.HxttResponse;
import com.david.mydemo.ctl_es.model.SmartSearchModel;
import com.david.mydemo.ctl_es.service.ISmartSearchService;
import com.david.mydemo.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;


@RestController
@Api(tags = "智能搜索controller")
@RequestMapping(value = "/smartSearch")
@Slf4j
public class SmartSearchController {

    @Value("${elasticsearch.searchMode}")
    private String searchMode;

    @Autowired
    private ISmartSearchService smartSearchService;

    @ApiOperation("搜索服务")
    @PostMapping("/search")
    public HxttResponse search(@RequestBody SmartSearchModel model) {
        if (StringUtils.isEmpty(model.getKeyword())) {
            log.error("未输入关键字，返回空数据。");
            return new HxttResponse().success();
        }
        if (StringUtils.isEmpty(model.getCountyCode())) {
            log.error("未输入区县编码，返回空数据。");
            return new HxttResponse().success();
        }
        ResponseResultDto searchResponse = null;
        String cityCode = smartSearchService.searchCityCode(model);
        if ("sql".equalsIgnoreCase(searchMode)) {
            searchResponse = smartSearchService.searchBySql(model);
        } else if ("es".equalsIgnoreCase(searchMode)) {
            searchResponse = smartSearchService.searchByEs(model);
        } else {
            log.error("服务搜索模式参数非法，searchMode={}", searchMode);
        }
        smartSearchService.insertLog("查询","地址查询模块","地址查询",model.getCountyCode(),new Date(), JSON.toJSONString(model),cityCode);
        return new HxttResponse().success(searchResponse);
    }

    @ApiOperation("示例搜索服务")
    @PostMapping("/searchByEsDemo")
    public HxttResponse searchByEsDemo(@RequestBody SmartSearchModel model) {
        if (StringUtils.isEmpty(model.getKeyword())) {
            log.info("未输入关键字，返回空数据。");
            return new HxttResponse().success();
        }
        ResponseEsDemoDto searchResponse = smartSearchService.searchByEsDemo(model);
        return new HxttResponse().success(searchResponse);
    }


}
